<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>情侣相册 - 爱情小窝</title>
    <script src="/Style/js/tailwindcss.js"></script>
    <link href="/Style/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#ec4899',
                        secondary: '#fce7f3',
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .photo-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 1.5rem;
            }
            .photo-card {
                @apply relative overflow-hidden rounded-xl shadow-md transition-all duration-300 hover:shadow-xl;
            }
            .photo-overlay {
                @apply absolute inset-0 bg-black bg-opacity-0 hover:bg-opacity-50 transition-all duration-300 flex items-center justify-center opacity-0 hover:opacity-100;
            }
            .album-card {
                @apply bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-md transition-all duration-300 transform hover:-translate-y-1;
            }
            .modal-small {
                max-width: 500px;
            }
            @media (max-width: 640px) {
                .modal-small {
                    max-width: calc(100% - 20px);
                }
            }
            .toast {
                @apply fixed bottom-4 left-1/2 transform -translate-x-1/2 px-4 py-2 rounded-lg z-50 transition-all duration-300;
            }
            .toast-success {
                @apply bg-green-500 text-white;
            }
            .toast-error {
                @apply bg-red-500 text-white;
            }
            .album-actions {
                @apply absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300;
            }
            .cover-selector {
				@apply border-4 border-transparent hover:border-primary/50 transition-all duration-300;
			}
			.cover-selected {
				@apply border-4 border-primary ring-2 ring-primary/30 transition-all duration-300;
			}
			.cover-select-overlay {
				@apply absolute inset-0 bg-primary/40 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity duration-300;
			}
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-md fixed w-full top-0 z-50">
        <div class="container mx-auto px-4 py-3">
            <div class="flex justify-between items-center">
                <div class="flex items-center">
                    <i class="fa fa-heart text-primary text-2xl mr-2"></i>
                    <span class="text-xl font-bold text-gray-800">Love Photo</span>
                </div>

                <div class="hidden md:flex space-x-8">
                    <a href="/" class="text-gray-700 hover:text-primary transition-colors py-2">首页</a>
                    <a href="/moments" class="text-gray-700 hover:text-primary transition-colors py-2">点点滴滴</a>
                    <a href="/photos" class="text-primary font-medium py-2 border-b-2 border-primary">Love Photo</a>
                    <a href="/lovelist" class="text-gray-700 hover:text-primary transition-colors py-2">Love List</a>
                    <a href="/messages" class="text-gray-700 hover:text-primary transition-colors py-2">留言板</a>
                    <a href="/couple" class="text-gray-700 hover:text-primary transition-colors py-2">爱情纪念</a>
                </div>

                <div class="flex items-center space-x-4">
                    <div class="relative">
                        <button id="user-menu-button" class="flex items-center space-x-2 focus:outline-none">
                            <img id="user-menu-avatar"
                                 src="{{ session.avatar if session.avatar else '/static/images/default_avatar.jpg' }}"
                                 alt="用户头像" class="w-8 h-8 rounded-full object-cover border-2 border-primary"
                                 onerror="this.src='/static/images/default_avatar.jpg'">
                            <span class="hidden md:inline text-gray-700">{{ session.nickname }}</span>
                            <i class="fa fa-chevron-down text-xs text-gray-500"></i>
                        </button>

                        <div id="user-menu" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10">
                            <a href="/profile" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">个人资料</a>
                            <a href="/logout" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                        </div>
                    </div>
                    <button id="mobile-menu-button" class="md:hidden text-gray-700">
                        <i class="fa fa-bars text-xl"></i>
                    </button>
                </div>
            </div>

            <!-- 移动端菜单 -->
            <div id="mobile-menu" class="hidden md:hidden mt-4 pb-2">
                <a href="/" class="block text-gray-700 hover:text-primary transition-colors py-2">首页</a>
                <a href="/moments" class="block text-gray-700 hover:text-primary transition-colors py-2">点点滴滴</a>
                <a href="/photos" class="block text-primary font-medium py-2">Love Photo</a>
                <a href="/lovelist" class="block text-gray-700 hover:text-primary transition-colors py-2">Love List</a>
                <a href="/messages" class="block text-gray-700 hover:text-primary transition-colors py-2">留言板</a>
                <a href="/couple" class="block text-gray-700 hover:text-primary transition-colors py-2">爱情纪念</a>
            </div>
        </div>
    </nav>

    <!-- 主内容 -->
    <main class="container mx-auto px-4 pt-24 pb-16">
        <div class="mb-8">
            <p class="text-gray-600">记录甜蜜爱情的每一个瞬间</p>
        </div>

        <!-- 功能按钮区 -->
        <div class="flex flex-wrap justify-between items-center mb-8 gap-4">
            <div class="flex items-center space-x-4">
                <button id="all-photos-btn" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition-all duration-300">
                    <i class="fa fa-th mr-2"></i>所有照片
                </button>
                <button id="albums-btn" class="px-4 py-2 bg-primary text-white rounded-lg transition-all duration-300">
                    <i class="fa fa-folder mr-2"></i>相册
                </button>
            </div>

            <div class="flex items-center space-x-4">
                <button id="create-album-btn" class="px-4 py-2 border border-primary text-primary rounded-lg hover:bg-primary/5 transition-all duration-300">
                    <i class="fa fa-folder-plus mr-2"></i>新建相册
                </button>
                <button id="upload-photo-btn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all duration-300">
                    <i class="fa fa-upload mr-2"></i>上传照片
                </button>
            </div>
        </div>

        <!-- 相册列表视图 - 默认展示 -->
        <div id="albums-view" class="mb-12">
            <h2 class="text-xl font-semibold text-gray-800 mb-6">我的相册</h2>

            <div id="albums-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- 加载状态 -->
                <div id="albums-loading" class="col-span-full text-center py-12">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                    <p class="text-gray-500">加载相册中...</p>
                </div>

                <!-- 空状态 -->
                <div id="no-albums" class="col-span-full text-center py-12 hidden">
                    <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-folder-open-o text-primary text-3xl"></i>
                    </div>
                    <p class="text-gray-600 mb-4">还没有创建相册</p>
                    <button id="create-first-album" class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-colors">
                        <i class="fa fa-plus mr-2"></i>创建第一个相册
                    </button>
                </div>
            </div>
        </div>

        <!-- 照片网格视图 -->
        <div id="photos-view" class="hidden">
            <!-- 筛选和分类 -->
            <div class="bg-white rounded-xl shadow-sm p-4 mb-6">
                <div class="flex flex-wrap items-center gap-4">
                    <div class="flex items-center">
                        <label class="text-gray-700 mr-2">分类:</label>
                        <select id="category-filter" class="border border-gray-300 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary">
                            <option value="">所有分类</option>
                            <option value="日常">日常</option>
                            <option value="旅行">旅行</option>
                            <option value="节日">节日</option>
                            <option value="特殊日子">特殊日子</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>

                    <div class="flex items-center">
                        <label class="text-gray-700 mr-2">相册:</label>
                        <select id="album-filter" class="border border-gray-300 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary">
                            <option value="">所有相册</option>
                            <!-- 动态填充相册 -->
                        </select>
                    </div>

                    <div class="flex items-center ml-auto">
                        <label class="text-gray-700 mr-2">排序:</label>
                        <select id="sort-by" class="border border-gray-300 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-primary">
                            <option value="newest">最新上传</option>
                            <option value="oldest">最早上传</option>
                            <option value="date_taken">拍摄日期</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- 照片网格 -->
            <div id="photos-container" class="photo-grid">
                <!-- 加载状态 -->
                <div id="photos-loading" class="col-span-full text-center py-12">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                    <p class="text-gray-500">加载照片中...</p>
                </div>

                <!-- 空状态 -->
                <div id="no-photos" class="col-span-full text-center py-12 hidden">
                    <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-camera text-primary text-3xl"></i>
                    </div>
                    <p class="text-gray-600 mb-4">还没有上传照片</p>
                    <button id="upload-first-photo" class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-colors">
                        <i class="fa fa-upload mr-2"></i>上传第一张照片
                    </button>
                </div>
            </div>
        </div>
    </main>

    <!-- 相册封面设置模态框 -->
    <div id="set-cover-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-lg w-full max-w-4xl mx-4 p-6 transform transition-all max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-gray-800" id="set-cover-album-name">设置相册封面</h3>
				<button id="close-set-cover" class="text-gray-500 hover:text-gray-700">
					<i class="fa fa-times mr-1"></i>关闭
				</button>
            </div>

            <p class="text-gray-600 mb-4">选择一张照片作为相册封面</p>

            <input type="hidden" id="set-cover-album-id">

            <div id="cover-photos-container" class="photo-grid">
                <!-- 加载状态 -->
                <div id="cover-loading" class="col-span-full text-center py-12">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                    <p class="text-gray-500">加载照片中...</p>
                </div>

                <!-- 空状态 -->
                <div id="no-cover-photos" class="col-span-full text-center py-12 hidden">
                    <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-camera text-primary text-3xl"></i>
                    </div>
                    <p class="text-gray-600 mb-4">该相册暂无照片</p>
                    <button id="upload-for-cover" class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-colors">
                        <i class="fa fa-upload mr-2"></i>上传照片
                    </button>
                </div>
            </div>

            <div class="mt-6 flex justify-end">
                <button id="confirm-set-cover" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    确认设置
                </button>
            </div>
        </div>
    </div>

    <!-- 上传照片模态框 -->
    <div id="upload-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-lg modal-small mx-4 p-6 transform transition-all max-h-[90vh] overflow-y-auto">
            <h3 class="text-xl font-bold text-gray-800 mb-4">上传照片</h3>
            <form id="upload-form" enctype="multipart/form-data">
               <div class="mb-4">
					<!-- 隐藏原生文件输入 -->
					<input type="file" id="photo-file" name="file" accept="image/*"
						   class="hidden" />
					
					<!-- 上传区域容器 -->
					<div class="flex flex-col space-y-2">
						<!-- 自定义上传按钮 -->
						<label for="photo-file" 
							   class="w-full px-4 py-2 border border-gray-300 rounded-lg text-center cursor-pointer hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-colors">
							选择图片
						</label>
						
						<!-- 文件名显示区域 -->
						<div id="file-name-display" class="text-sm text-gray-600 italic">
							未选择图片
						</div>
					</div>
				</div>
					

                <div class="mb-4">
                    <label for="photo-album" class="block text-gray-700 mb-2">选择相册</label>
                    <select id="photo-album" name="album_id"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <!-- 动态填充相册 -->
                        </select>
                </div>

                <div class="mb-4">
                    <label for="photo-title" class="block text-gray-700 mb-2">照片标题</label>
                    <input type="text" id="photo-title" name="title"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                           placeholder="给照片起个名字...">
                </div>

                <!-- 紧凑布局：将分类和日期放在同一行 -->
                <div class="mb-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="photo-category" class="block text-gray-700 mb-2">分类</label>
                        <select id="photo-category" name="category"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">请选择分类</option>
                            <option value="日常">日常</option>
                            <option value="旅行">旅行</option>
                            <option value="节日">节日</option>
                            <option value="特殊日子">特殊日子</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                    <div>
                        <label for="photo-date" class="block text-gray-700 mb-2">拍摄日期</label>
                        <input type="date" id="photo-date" name="date_taken"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                    </div>
                </div>

                <div class="mb-4">
                    <label for="photo-description" class="block text-gray-700 mb-2">描述</label>
                    <textarea id="photo-description" name="description" rows="2"
                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                              placeholder="描述一下这张照片的故事..."></textarea>
                </div>

                <div class="mb-6">
                    <label class="inline-flex items-center">
                        <input type="checkbox" id="photo-is-shared" name="is_shared" checked
                               class="form-checkbox h-5 w-5 text-primary rounded">
                        <span class="ml-2 text-gray-700">共享给情侣查看</span>
                    </label>
                </div>

                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancel-upload"
                            class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                        取消
                    </button>
                    <button type="submit" id="submit-upload"
                            class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                        上传照片
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 创建相册模态框 -->
    <div id="create-album-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-lg w-full max-w-md mx-4 p-6 transform transition-all">
            <h3 class="text-xl font-bold text-gray-800 mb-4">创建相册</h3>

            <form id="create-album-form">
                <div class="mb-4">
                    <label for="album-name" class="block text-gray-700 mb-2">相册名称 <span class="text-red-500">*</span></label>
                    <input type="text" id="album-name" name="name"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                           placeholder="例如：我们的旅行、日常点滴">
                </div>

                <div class="mb-4">
                    <label for="album-description" class="block text-gray-700 mb-2">相册描述</label>
                    <textarea id="album-description" name="description" rows="3"
                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                              placeholder="描述一下这个相册..."></textarea>
                </div>

                <div class="mb-6">
                    <label class="inline-flex items-center">
                        <input type="checkbox" id="album-is-shared" name="is_shared" checked
                               class="form-checkbox h-5 w-5 text-primary rounded">
                        <span class="ml-2 text-gray-700">共享给情侣查看</span>
                    </label>
                </div>

                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancel-create-album"
                            class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                        取消
                    </button>
                    <button type="submit" id="submit-create-album"
                            class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                        创建相册
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 照片详情和编辑模态框 -->
    <div id="photo-detail-modal" class="fixed inset-0 bg-black/90 flex items-center justify-center z-50 hidden">
        <div class="relative w-full max-w-4xl px-4 py-8">
            <button id="close-photo-detail" class="absolute top-4 right-4 text-white text-2xl hover:text-gray-300 transition-colors">
                <i class="fa fa-times"></i>
            </button>

            <div class="bg-white rounded-xl shadow-lg overflow-hidden ">
                <div class="md:flex">
                    <div class="md:w-2/3 bg-gray-100 flex items-center justify-center p-4">
                        <img id="detail-photo-img" src="" alt="照片详情" class="max-w-full object-contain max-h-[40vh] overflow-y-auto">
                    </div>

                    <!-- 照片信息和编辑区 -->
                    <div class="md:w-1/3 p-6 max-h-[40vh]  overflow-y-auto">
                        <!-- 详情视图 -->
                        <div id="photo-detail-view">
                            <h3 id="detail-photo-title" class="text-xl font-bold text-gray-800 mb-2"></h3>

                            <div class="mb-4 text-sm text-gray-600">
                                <p id="detail-photo-uploader" class="mb-1"></p>
                                <p id="detail-photo-date" class="mb-1"></p>
                                <p id="detail-photo-category" class="mb-1"></p>
                                <p id="detail-photo-album" class="mb-1"></p>
                            </div>

                            <div class="mb-4">
                                <h5 class="font-medium text-gray-700 mb-2">描述</h5>
                                <p id="detail-photo-description" class="text-gray-600"></p>
                            </div>

                            <div class="border-t border-gray-200 pt-4">
                                <div class="flex justify-between items-center mb-4">
                                    <label class="inline-flex items-center">
                                        <input type="checkbox" id="detail-photo-is-shared"
                                               class="form-checkbox h-5 w-5 text-primary rounded">
                                        <span class="ml-2 text-gray-700">共享给情侣</span>
                                    </label>
                                </div>

                                <div class="flex space-x-3">
                                    <button id="edit-photo-btn" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">
                                        <i class="fa fa-edit mr-1"></i> 编辑
                                    </button>
                                    <button id="delete-photo-btn" class="flex-1 px-4 py-2 border border-red-300 text-red-600 rounded-lg hover:bg-red-50 transition-colors">
                                        <i class="fa fa-trash mr-1"></i> 删除
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 编辑视图 -->
                        <div id="photo-edit-view" class="hidden" >
                            <h3 class="text-xl font-bold text-gray-800 mb-4">编辑照片</h3>

                            <form id="edit-photo-form">
                                <input type="hidden" id="edit-photo-id">

                                <div class="mb-4">
                                    <label for="edit-photo-title" class="block text-gray-700 mb-2">照片标题</label>
                                    <input type="text" id="edit-photo-title"
                                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                                </div>

                                <div class="mb-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="edit-photo-category" class="block text-gray-700 mb-2">分类</label>
                                        <select id="edit-photo-category"
                                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                                            <option value="">请选择分类</option>
                                            <option value="日常">日常</option>
                                            <option value="旅行">旅行</option>
                                            <option value="节日">节日</option>
                                            <option value="特殊日子">特殊日子</option>
                                            <option value="其他">其他</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="edit-photo-date" class="block text-gray-700 mb-2">拍摄日期</label>
                                        <input type="date" id="edit-photo-date"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                                    </div>
                                </div>

                                <div class="mb-4">
                                    <label for="edit-photo-description" class="block text-gray-700 mb-2">描述</label>
                                    <textarea id="edit-photo-description" rows="2"
                                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"></textarea>
                                </div>

                                <div class="mb-6">
                                    <label class="inline-flex items-center">
                                        <input type="checkbox" id="edit-photo-is-shared"
                                               class="form-checkbox h-5 w-5 text-primary rounded">
                                        <span class="ml-2 text-gray-700">共享给情侣查看</span>
                                    </label>
                                </div>

                                <div class="flex space-x-3">
                                    <button type="button" id="cancel-edit-photo" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">
                                        取消
                                    </button>
                                    <button type="submit" class="flex-1 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                                        保存修改
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框（通用） -->
    <div id="delete-confirm-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-lg w-full max-w-md mx-4 p-6 transform transition-all">
            <h3 class="text-xl font-bold text-gray-800 mb-4" id="delete-modal-title">确认删除</h3>

            <p class="text-gray-600 mb-6" id="delete-modal-message">您确定要执行此操作吗？此操作无法撤销。</p>

            <input type="hidden" id="delete-item-id">
            <input type="hidden" id="delete-item-type"> <!-- 'photo' 或 'album' -->

            <div class="flex justify-end space-x-3">
                <button id="cancel-delete"
                        class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button id="confirm-delete"
                        class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                    确认删除
                </button>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-10">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-6 md:mb-0">
                    <div class="flex items-center mb-2">
                        <i class="fa fa-heart text-primary text-2xl mr-2"></i>
                        <span class="text-xl font-bold">情侣相册</span>
                    </div>
                    <p class="text-gray-400">记录甜蜜爱情的每一个瞬间</p>
                </div>
            </div>

            <div class="border-t border-gray-700 mt-8 pt-8 text-center text-gray-400 text-sm">
                <p>© 2025 爱情小窝 - 让爱情更甜蜜</p>
            </div>
        </div>
    </footer>

    <!-- JavaScript -->
    <script src="/Style/js/axios.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 页面元素引用 - 确保所有元素都存在
            const elements = {
                albumsView: document.getElementById('albums-view'),
                photosView: document.getElementById('photos-view'),
                albumsBtn: document.getElementById('albums-btn'),
                allPhotosBtn: document.getElementById('all-photos-btn'),
                uploadPhotoBtn: document.getElementById('upload-photo-btn'),
                createAlbumBtn: document.getElementById('create-album-btn'),
                createFirstAlbumBtn: document.getElementById('create-first-album'),
                uploadFirstPhotoBtn: document.getElementById('upload-first-photo'),
                uploadModal: document.getElementById('upload-modal'),
                createAlbumModal: document.getElementById('create-album-modal'),
                photoDetailModal: document.getElementById('photo-detail-modal'),
                deleteConfirmModal: document.getElementById('delete-confirm-modal'),
                setCoverModal: document.getElementById('set-cover-modal'),
                userMenuButton: document.getElementById('user-menu-button'),
                userMenu: document.getElementById('user-menu'),
                mobileMenuButton: document.getElementById('mobile-menu-button'),
                mobileMenu: document.getElementById('mobile-menu'),
                categoryFilter: document.getElementById('category-filter'),
                albumFilter: document.getElementById('album-filter'),
                sortBy: document.getElementById('sort-by'),
                albumsContainer: document.getElementById('albums-container'),
                albumsLoading: document.getElementById('albums-loading'),
                noAlbums: document.getElementById('no-albums'),
                photosContainer: document.getElementById('photos-container'),
                photosLoading: document.getElementById('photos-loading'),
                noPhotos: document.getElementById('no-photos'),
                photoAlbum: document.getElementById('photo-album'),
                submitCreateAlbum: document.getElementById('submit-create-album'),
                submitUpload: document.getElementById('submit-upload'),
                cancelUpload: document.getElementById('cancel-upload'),
                cancelCreateAlbum: document.getElementById('cancel-create-album'),
                closePhotoDetail: document.getElementById('close-photo-detail'),
                cancelDelete: document.getElementById('cancel-delete'),
                confirmDelete: document.getElementById('confirm-delete'),
                editPhotoBtn: document.getElementById('edit-photo-btn'),
                cancelEditPhoto: document.getElementById('cancel-edit-photo'),
                editPhotoForm: document.getElementById('edit-photo-form'),
                deletePhotoBtn: document.getElementById('delete-photo-btn'),
                detailPhotoIsShared: document.getElementById('detail-photo-is-shared'),
                setCoverAlbumName: document.getElementById('set-cover-album-name'),
                setCoverAlbumId: document.getElementById('set-cover-album-id'),
                coverPhotosContainer: document.getElementById('cover-photos-container'),
                coverLoading: document.getElementById('cover-loading'),
                noCoverPhotos: document.getElementById('no-cover-photos'),
                closeSetCover: document.getElementById('close-set-cover'),
                confirmSetCover: document.getElementById('confirm-set-cover'),
                uploadForCover: document.getElementById('upload-for-cover')
            };

            // 检查元素是否存在的辅助函数
            function elementExists(el) {
                return el !== null;
            }

            // 事件监听 - 用户菜单切换
            if (elementExists(elements.userMenuButton) && elementExists(elements.userMenu)) {
                elements.userMenuButton.addEventListener('click', function() {
                    elements.userMenu.classList.toggle('hidden');
                });

                // 点击页面其他地方关闭用户菜单
                document.addEventListener('click', function(event) {
                    if (!elements.userMenuButton.contains(event.target) && !elements.userMenu.contains(event.target)) {
                        elements.userMenu.classList.add('hidden');
                    }
                });
            }

            // 事件监听 - 移动端菜单切换
            if (elementExists(elements.mobileMenuButton) && elementExists(elements.mobileMenu)) {
                elements.mobileMenuButton.addEventListener('click', function() {
                    elements.mobileMenu.classList.toggle('hidden');
                });
            }

            // 事件监听 - 视图切换
            if (elementExists(elements.albumsBtn) && elementExists(elements.allPhotosBtn)) {
                elements.albumsBtn.addEventListener('click', function() {
                    if (elementExists(elements.albumsView)) elements.albumsView.classList.remove('hidden');
                    if (elementExists(elements.photosView)) elements.photosView.classList.add('hidden');

                    elements.albumsBtn.classList.add('bg-primary', 'text-white');
                    elements.albumsBtn.classList.remove('border', 'border-gray-300', 'hover:bg-gray-100');
                    elements.allPhotosBtn.classList.remove('bg-primary', 'text-white');
                    elements.allPhotosBtn.classList.add('border', 'border-gray-300', 'hover:bg-gray-100');

                    loadAlbums();
                });

                elements.allPhotosBtn.addEventListener('click', function() {
                    if (elementExists(elements.albumsView)) elements.albumsView.classList.add('hidden');
                    if (elementExists(elements.photosView)) elements.photosView.classList.remove('hidden');

                    elements.allPhotosBtn.classList.add('bg-primary', 'text-white');
                    elements.allPhotosBtn.classList.remove('border', 'border-gray-300', 'hover:bg-gray-100');
                    elements.albumsBtn.classList.remove('bg-primary', 'text-white');
                    elements.albumsBtn.classList.add('border', 'border-gray-300', 'hover:bg-gray-100');
					loadPhotosWithFilters();
                    // loadPhotos();
                });
            }

            // 事件监听 - 模态框控制
            if (elementExists(elements.uploadPhotoBtn) && elementExists(elements.uploadModal)) {
                elements.uploadPhotoBtn.addEventListener('click', function() {
                    elements.uploadModal.classList.remove('hidden');
                    loadAlbumsForSelect();
                });
            }

            if (elementExists(elements.createAlbumBtn) && elementExists(elements.createAlbumModal)) {
                elements.createAlbumBtn.addEventListener('click', function() {
                    elements.createAlbumModal.classList.remove('hidden');
                });
            }

            if (elementExists(elements.createFirstAlbumBtn) && elementExists(elements.createAlbumModal)) {
                elements.createFirstAlbumBtn.addEventListener('click', function() {
                    elements.createAlbumModal.classList.remove('hidden');
                });
            }

            if (elementExists(elements.uploadFirstPhotoBtn) && elementExists(elements.uploadModal)) {
                elements.uploadFirstPhotoBtn.addEventListener('click', function() {
                    elements.uploadModal.classList.remove('hidden');
                    loadAlbumsForSelect();
                });
            }

            // 关闭模态框
            if (elementExists(elements.cancelUpload) && elementExists(elements.uploadModal)) {
                elements.cancelUpload.addEventListener('click', function() {
                    elements.uploadModal.classList.add('hidden');
                });
            }

            if (elementExists(elements.cancelCreateAlbum) && elementExists(elements.createAlbumModal)) {
                elements.cancelCreateAlbum.addEventListener('click', function() {
                    elements.createAlbumModal.classList.add('hidden');
                });
            }

            if (elementExists(elements.closePhotoDetail) && elementExists(elements.photoDetailModal)) {
                elements.closePhotoDetail.addEventListener('click', function() {
                    // 切换回详情视图
                    const photoDetailView = document.getElementById('photo-detail-view');
                    const photoEditView = document.getElementById('photo-edit-view');
                    if (elementExists(photoDetailView)) photoDetailView.classList.remove('hidden');
                    if (elementExists(photoEditView)) photoEditView.classList.add('hidden');

                    elements.photoDetailModal.classList.add('hidden');
                });
            }

            if (elementExists(elements.cancelDelete) && elementExists(elements.deleteConfirmModal)) {
                elements.cancelDelete.addEventListener('click', function() {
                    elements.deleteConfirmModal.classList.add('hidden');
                });
            }

            // 照片编辑相关
            if (elementExists(elements.editPhotoBtn)) {
                elements.editPhotoBtn.addEventListener('click', function() {
                    const photoDetailView = document.getElementById('photo-detail-view');
                    const photoEditView = document.getElementById('photo-edit-view');
                    if (elementExists(photoDetailView)) photoDetailView.classList.add('hidden');
                    if (elementExists(photoEditView)) photoEditView.classList.remove('hidden');
                });
            }

            if (elementExists(elements.cancelEditPhoto)) {
                elements.cancelEditPhoto.addEventListener('click', function() {
                    const photoEditView = document.getElementById('photo-edit-view');
                    const photoDetailView = document.getElementById('photo-detail-view');
                    if (elementExists(photoEditView)) photoEditView.classList.add('hidden');
                    if (elementExists(photoDetailView)) photoDetailView.classList.remove('hidden');
                });
            }

            if (elementExists(elements.editPhotoForm)) {
                elements.editPhotoForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    savePhotoChanges();
                });
            }

            // 点击模态框外部关闭
            if (elementExists(elements.uploadModal)) {
                elements.uploadModal.addEventListener('click', function(event) {
                    if (event.target === elements.uploadModal) {
                        elements.uploadModal.classList.add('hidden');
                    }
                });
            }

            if (elementExists(elements.createAlbumModal)) {
                elements.createAlbumModal.addEventListener('click', function(event) {
                    if (event.target === elements.createAlbumModal) {
                        elements.createAlbumModal.classList.add('hidden');
                    }
                });
            }

            if (elementExists(elements.photoDetailModal)) {
                elements.photoDetailModal.addEventListener('click', function(event) {
                    if (event.target === elements.photoDetailModal) {
                        const photoDetailView = document.getElementById('photo-detail-view');
                        const photoEditView = document.getElementById('photo-edit-view');
                        if (elementExists(photoDetailView)) photoDetailView.classList.remove('hidden');
                        if (elementExists(photoEditView)) photoEditView.classList.add('hidden');

                        elements.photoDetailModal.classList.add('hidden');
                    }
                });
            }

            if (elementExists(elements.deleteConfirmModal)) {
                elements.deleteConfirmModal.addEventListener('click', function(event) {
                    if (event.target === elements.deleteConfirmModal) {
                        elements.deleteConfirmModal.classList.add('hidden');
                    }
                });
            }

            // 相册封面设置模态框控制
            if (elementExists(elements.closeSetCover) && elementExists(elements.setCoverModal)) {
				elements.closeSetCover.addEventListener('click', function() {
					resetCoverModalState();
					elements.setCoverModal.classList.add('hidden');
				});
			}
			
			
			// 为模态框外部点击关闭添加处理
			if (elementExists(elements.setCoverModal)) {
				elements.setCoverModal.addEventListener('click', function(event) {
					if (event.target === elements.setCoverModal) {
						resetCoverModalState();
						elements.setCoverModal.classList.add('hidden');
					}
				});
			}

			// 添加重置模态框状态的函数
			function resetCoverModalState() {
				// 清除所有选中状态
				document.querySelectorAll('.cover-selected').forEach(el => {
					el.classList.remove('cover-selected');
					el.classList.add('cover-selector');
				});
				// 禁用确认按钮
				if (elementExists(elements.confirmSetCover)) {
					elements.confirmSetCover.disabled = true;
				}
			}

            if (elementExists(elements.uploadForCover) && elementExists(elements.setCoverModal) && elementExists(elements.uploadModal)) {
                elements.uploadForCover.addEventListener('click', function() {
                    // 关闭封面设置模态框
                    elements.setCoverModal.classList.add('hidden');
                    // 打开上传照片模态框，并设置当前相册
                    elements.uploadModal.classList.remove('hidden');
                    loadAlbumsForSelect(elements.setCoverAlbumId.value);
                });
            }

            // 确认设置封面
            if (elementExists(elements.confirmSetCover)) {
                elements.confirmSetCover.addEventListener('click', function() {
                    const albumId = elements.setCoverAlbumId.value;
                    const selectedPhotoId = document.querySelector('.cover-selected')?.getAttribute('data-photo-id');

                    if (albumId && selectedPhotoId) {
                        setAlbumCover(albumId, selectedPhotoId);
                    }
                });
            }

            // 表单提交 - 创建相册
            const createAlbumForm = document.getElementById('create-album-form');
            if (elementExists(createAlbumForm)) {
                createAlbumForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    createAlbum();
                });
            }

            // 表单提交 - 上传照片
            const uploadForm = document.getElementById('upload-form');
            if (elementExists(uploadForm)) {
                uploadForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    uploadPhoto();
                });
            }

            // 通用删除确认
            if (elementExists(elements.confirmDelete)) {
                elements.confirmDelete.addEventListener('click', function() {
                    const itemId = document.getElementById('delete-item-id')?.value;
                    const itemType = document.getElementById('delete-item-type')?.value;

                    if (itemId && itemType) {
                        if (itemType === 'photo') {
                            deletePhoto(itemId);
                        } else if (itemType === 'album') {
                            deleteAlbum(itemId);
                        }
                    }
                });
            }

            // 筛选器变化时重新加载照片
            if (elementExists(elements.categoryFilter)) {
                elements.categoryFilter.addEventListener('change', function() {
                    loadPhotosWithFilters();
                });
            }

            if (elementExists(elements.albumFilter)) {
                elements.albumFilter.addEventListener('change', function() {
                    loadPhotosWithFilters();
                });
            }

            if (elementExists(elements.sortBy)) {
                elements.sortBy.addEventListener('change', function() {
                    loadPhotosWithFilters();
                });
            }

            // 照片删除按钮事件
            if (elementExists(elements.deletePhotoBtn) && elementExists(elements.photoDetailModal) && elementExists(elements.deleteConfirmModal)) {
                elements.deletePhotoBtn.addEventListener('click', function() {
                    elements.photoDetailModal.classList.add('hidden');
                    const photoId = document.getElementById('edit-photo-id')?.value;
                    if (photoId) {
                        showDeletePhotoConfirm(photoId);
                    }
                });
            }

            // 共享状态变更事件
            if (elementExists(elements.detailPhotoIsShared)) {
                elements.detailPhotoIsShared.addEventListener('change', function() {
                    const photoId = document.getElementById('edit-photo-id')?.value;
                    if (photoId) {
                        updatePhotoSharedStatus(photoId, this.checked);
                    }
                });
            }
             
            // 初始加载 - 默认展示相册
            loadAlbums();
            loadAlbumsForFilter();

            // 加载相册列表 - 支持设置封面
            function loadAlbums() {
                if (!elementExists(elements.albumsContainer) || !elementExists(elements.albumsLoading) || !elementExists(elements.noAlbums)) {
                    console.error('相册相关元素不存在');
                    return;
                }

                elements.albumsLoading.classList.remove('hidden');
                elements.noAlbums.classList.add('hidden');
                elements.albumsContainer.innerHTML = '';

                axios.get('/api/albums')
                    .then(response => {
                        elements.albumsLoading.classList.add('hidden');
                        // 确保处理单个相册对象和相册数组两种情况
                        const albums = Array.isArray(response.data) ? response.data : [response.data];

                        if (albums.length === 0) {
                            elements.noAlbums.classList.remove('hidden');
                            return;
                        }

                        albums.forEach(album => {
                            // 获取相册封面照片，如果没有则使用默认图片
                            console.info(album.cover_image_url );
                            const coverPhoto = album.cover_image_url ? album.cover_image_url : `https://picsum.photos/400/300?random=${album.id}`;

                            const albumCard = document.createElement('div');
                            albumCard.className = 'album-card group';

                            albumCard.innerHTML = `
                                <div class="h-48 bg-gray-100 relative overflow-hidden">
                                    <img src="${coverPhoto}" alt="${album.name}"
                                         class="w-full h-full object-cover">
                                    <div class="absolute top-3 right-3 bg-black/50 text-white text-sm px-2 py-1 rounded">
                                        ${album.photo_count} 张照片
                                    </div>
                                    ${album.is_shared ? '<div class="absolute top-3 left-3 bg-primary/80 text-white text-xs px-2 py-1 rounded">共享</div>' : ''}
                                    <!-- 相册操作按钮 -->
                                    <div class="album-actions flex space-x-2">
                                        <button class="bg-white/80 hover:bg-white text-gray-800 p-2 rounded-full shadow-md transition-colors"
                                                onclick="event.stopPropagation(); openSetCoverModal(${album.id}, '${escapeHtml(album.name)}')">
                                            <i class="fa fa-image"></i>
                                        </button>
                                        <button class="bg-white/80 hover:bg-white text-gray-800 p-2 rounded-full shadow-md transition-colors"
                                                onclick="event.stopPropagation(); showDeleteAlbumConfirm(${album.id}, '${escapeHtml(album.name)}')">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="p-4">
                                    <h3 class="font-bold text-gray-800 mb-1">${album.name}</h3>
                                    <p class="text-sm text-gray-600 mb-3 line-clamp-2">${album.description || '无描述'}</p>
                                    <div class="flex justify-between items-center">
                                        <span class="text-xs text-gray-500">
                                            创建于 ${formatDate(album.created_at)}
                                        </span>
                                        <button class="text-primary hover:text-primary/80 transition-colors"
                                                onclick="event.stopPropagation(); viewAlbumPhotos(${album.id})">
                                            查看照片
                                        </button>
                                    </div>
                                </div>
                            `;

                            elements.albumsContainer.appendChild(albumCard);

                            // 点击相册卡片查看照片
                            albumCard.addEventListener('click', function() {
                                viewAlbumPhotos(album.id);
                            });
                        });
                    })
                    .catch(error => {
                        console.error('加载相册失败:', error);
                        elements.albumsLoading.classList.add('hidden');
                        elements.albumsContainer.innerHTML = '<p class="text-red-500">加载相册失败，请重试</p>';
                    });
            }

            // 加载照片网格
            function loadPhotos() {
                if (!elementExists(elements.photosContainer) || !elementExists(elements.photosLoading) || !elementExists(elements.noPhotos)) {
                    console.error('照片相关元素不存在');
                    return;
                }

                elements.photosLoading.classList.remove('hidden');
                elements.noPhotos.classList.add('hidden');
                elements.photosContainer.innerHTML = '';

                axios.get('/api/photos/shared')
                    .then(response => {
                        processPhotosResponse(response, elements.photosContainer, elements.photosLoading, elements.noPhotos);
                    })
                    .catch(error => {
                        handlePhotoLoadError(error, elements.photosLoading, elements.photosContainer);
                    });
            }

            // 带筛选条件加载照片
            function loadPhotosWithFilters() {
                if (!elementExists(elements.photosContainer) || !elementExists(elements.photosLoading) || !elementExists(elements.noPhotos) || !elementExists(elements.albumFilter) || !elementExists(elements.categoryFilter) || !elementExists(elements.sortBy)) {
                    console.error('照片筛选相关元素不存在');
                    return;
                }

                const category = elements.categoryFilter.value;
                const albumId = elements.albumFilter.value;
                const sortBy = elements.sortBy.value;

                elements.photosLoading.classList.remove('hidden');
                elements.noPhotos.classList.add('hidden');
                elements.photosContainer.innerHTML = '';

                let url = '/api/photos';
                if (albumId) {
                    url = `/api/albums/${albumId}/photos`;
                }

                axios.get(url, {
                    params: {
                        category: category,
                        sort_by: sortBy
                    }
                })
                .then(response => {
                    processPhotosResponse(response, elements.photosContainer, elements.photosLoading, elements.noPhotos);
                })
                .catch(error => {
                    handlePhotoLoadError(error, elements.photosLoading, elements.photosContainer);
                });
            }

            // 处理照片响应数据
            function processPhotosResponse(response, container, loading, noItems) {
                loading.classList.add('hidden');
                const photos = response.data;

                if (!photos || photos.length === 0) {
                    noItems.classList.remove('hidden');
                    return;
                }

                photos.forEach(photo => {
                    const photoCard = document.createElement('div');
                    photoCard.className = 'photo-card group cursor-pointer';
                    photoCard.setAttribute('data-id', photo.id);

                    photoCard.innerHTML = `
                        <div class="aspect-square bg-gray-100 overflow-hidden">
                            <img src="${photo.image_url}" alt="${photo.title}"
                                 class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110">
                            <div class="photo-overlay">
                                <button class="bg-white text-gray-800 p-2 rounded-full mx-1 hover:bg-gray-100 transition-colors"
                                        onclick="event.stopPropagation(); showPhotoDetail(${photo.id})">
                                    <i class="fa fa-eye"></i>
                                </button>
                                <button class="bg-white text-gray-800 p-2 rounded-full mx-1 hover:bg-gray-100 transition-colors"
                                        onclick="event.stopPropagation(); showDeletePhotoConfirm(${photo.id})">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                            ${photo.is_shared ? '<div class="absolute top-2 left-2 bg-primary/80 text-white text-xs px-2 py-0.5 rounded">共享</div>' : ''}
                        </div>
                        <div class="p-3">
                            <h3 class="font-medium text-gray-800 truncate">${photo.title}</h3>
                            <p class="text-xs text-gray-500">${photo.date_taken ? new Date(photo.date_taken).toLocaleDateString() : ''}</p>
                        </div>
                    `;

                    container.appendChild(photoCard);

                    // 点击照片查看详情
                    photoCard.addEventListener('click', function() {
                        showPhotoDetail(photo.id);
                    });
                });
            }

            // 处理照片加载错误
            function handlePhotoLoadError(error, loading, container) {
                console.error('加载照片失败:', error);
                loading.classList.add('hidden');
                container.innerHTML = '<p class="text-red-500">加载照片失败，请重试</p>';
            }

            // 加载相册到下拉框
            function loadAlbumsForSelect(selectedAlbumId = null) {
                const albumSelect = document.getElementById('photo-album');
                if (!elementExists(albumSelect)) {
                    console.error('相册选择下拉框不存在');
                    return;
                }

                albumSelect.innerHTML = '<option value="">请选择相册</option>';

                axios.get('/api/albums')
                    .then(response => {
                        const albums = Array.isArray(response.data) ? response.data : [response.data];

                        albums.forEach(album => {
                            const option = document.createElement('option');
                            option.value = album.id;
                            option.textContent = album.name;
                            // 如果指定了选中的相册，则设置选中状态
                            if (selectedAlbumId && album.id == selectedAlbumId) {
                                option.selected = true;
                            }
                            albumSelect.appendChild(option);
                        });
                    })
                    .catch(error => {
                        console.error('加载相册失败:', error);
                        showToast('加载相册列表失败，请刷新页面重试', 'error');
                    });
            }

            // 加载相册到筛选器
            function loadAlbumsForFilter() {
                if (!elementExists(elements.albumFilter)) {
                    console.error('相册筛选下拉框不存在');
                    return;
                }

                // 保存当前选中的值
                const currentValue = elements.albumFilter.value;

                // 清空现有选项（保留"所有相册"）
                elements.albumFilter.innerHTML = '<option value="">所有相册</option>';

                axios.get('/api/albums')
                    .then(response => {
                        const albums = Array.isArray(response.data) ? response.data : [response.data];

                        albums.forEach(album => {
                            const option = document.createElement('option');
                            option.value = album.id;
                            option.textContent = album.name;
                            elements.albumFilter.appendChild(option);
                        });

                        // 恢复选中值
                        if (currentValue) {
                            elements.albumFilter.value = currentValue;
                        }
                    })
                    .catch(error => {
                        console.error('加载相册失败:', error);
                    });
            }

            // 创建相册
            function createAlbum() {
                const nameInput = document.getElementById('album-name');
                const descriptionInput = document.getElementById('album-description');
                const isSharedInput = document.getElementById('album-is-shared');
                const createAlbumForm = document.getElementById('create-album-form');

                if (!elementExists(nameInput) || !elementExists(descriptionInput) || !elementExists(isSharedInput) || !elementExists(elements.submitCreateAlbum)) {
                    console.error('创建相册表单元素不存在');
                    return;
                }

                const name = nameInput.value.trim();
                if (!name) {
                    showToast('请输入相册名称', 'error');
                    return;
                }

                const albumData = {
                    name: name,
                    description: descriptionInput.value.trim(),
                    is_shared: isSharedInput.checked
                };

                // 显示加载状态
                const originalText = elements.submitCreateAlbum.innerHTML;
                elements.submitCreateAlbum.disabled = true;
                elements.submitCreateAlbum.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>创建中...';

                axios.post('/api/albums', albumData)
                    .then(response => {
                        showToast('相册创建成功');
                        if (elementExists(elements.createAlbumModal)) elements.createAlbumModal.classList.add('hidden');
                        if (elementExists(createAlbumForm)) createAlbumForm.reset();

                        // 恢复按钮状态
                        elements.submitCreateAlbum.disabled = false;
                        elements.submitCreateAlbum.innerHTML = originalText;

                        // 同步更新所有相关视图
                        syncAllViews();
                    })
                    .catch(error => {
                        console.error('创建相册失败:', error);
                        showToast('创建相册失败，请重试', 'error');

                        // 恢复按钮状态
                        elements.submitCreateAlbum.disabled = false;
                        elements.submitCreateAlbum.innerHTML = originalText;
                    });
            }
             
             
             // 监听文件选择事件
			document.getElementById('photo-file').addEventListener('change', function(e) {
				const fileNameDisplay = document.getElementById('file-name-display');
				const photoAlbum = document.getElementById('photo-album');
				const photoCategory = document.getElementById('photo-category');
				const dateInput = document.getElementById('photo-date');
				if (e.target.files.length > 0) {
					// 显示选中的文件名
					const fileName = e.target.files[0].name;
					fileNameDisplay.textContent = `已选择: ${fileName}`;
					fileNameDisplay.classList.remove('italic', 'text-gray-400');
					fileNameDisplay.classList.add('text-gray-700','font-medium');
					const today = new Date();
    
					// 格式化日期为 YYYY-MM-DD 格式（input[type="date"] 要求的格式）
					const year = today.getFullYear();
					const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1并补零
					const day = String(today.getDate()).padStart(2, '0'); // 日期补零
					
					const formattedDate = `${year}-${month}-${day}`;
					
					// 设置输入框默认值
					dateInput.value = formattedDate;
					
					// 自动选择第一个相册
					if (photoAlbum.options.length > 1) {
						photoAlbum.selectedIndex = 1;
					}

					// 自动选择第一个分类
					if (photoCategory.options.length > 1) {
						photoCategory.selectedIndex = 1;
					}
				} else {
					// 未选择文件时的状态
					fileNameDisplay.textContent = '未选择图片';
					fileNameDisplay.classList.add('italic', 'text-gray-400');
					fileNameDisplay.classList.remove('text-gray-700');
				}
			});
			
            // 上传照片
            function uploadPhoto() {
                const fileInput = document.getElementById('photo-file');
                const albumSelect = document.getElementById('photo-album');
                const uploadForm = document.getElementById('upload-form');

                if (!elementExists(fileInput) || !elementExists(albumSelect) || !elementExists(elements.submitUpload)) {
                    console.error('上传照片表单元素不存在');
                    return;
                }

                if (!fileInput.files[0]) {
                    showToast('请选择要上传的照片', 'error');
                    return;
                }

                if (!albumSelect.value) {
                    showToast('请选择相册', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('file', fileInput.files[0]);
                formData.append('album_id', albumSelect.value);
                formData.append('title', document.getElementById('photo-title')?.value.trim() || '');
                formData.append('description', document.getElementById('photo-description')?.value.trim() || '');
                formData.append('category', document.getElementById('photo-category')?.value || '');
                formData.append('date_taken', document.getElementById('photo-date')?.value || '');
                formData.append('is_shared', document.getElementById('photo-is-shared')?.checked || false);

                // 显示上传进度
                const originalText = elements.submitUpload.innerHTML;
                elements.submitUpload.disabled = true;
                elements.submitUpload.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>上传中...';

                axios.post('/api/photos', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    onUploadProgress: function(progressEvent) {
                        const percentCompleted = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        );
                        elements.submitUpload.innerHTML = `<i class="fa fa-spinner fa-spin mr-2"></i>上传中...${percentCompleted}%`;
                    }
                })
                .then(response => {
                    showToast('照片上传成功');
                    if (elementExists(elements.uploadModal)) elements.uploadModal.classList.add('hidden');
                    // 重置表单
                    if (elementExists(uploadForm)) uploadForm.reset();
                    // 恢复按钮状态
                    elements.submitUpload.disabled = false;
                    elements.submitUpload.innerHTML = originalText;
                    // 同步更新所有相关视图
                    syncAllViews();
                })
                .catch(error => {
                    console.error('上传照片失败:', error);
                    showToast('上传照片失败，请重试', 'error');
                    // 恢复按钮状态
                    if (elementExists(elements.submitUpload)) {
                        elements.submitUpload.disabled = false;
                        elements.submitUpload.innerHTML = originalText;
                    }
                });
            }

            // 显示照片详情
            function showPhotoDetail(photoId) {
                if (!elementExists(elements.photoDetailModal)) {
                    console.error('照片详情模态框不存在');
                    return;
                }

                axios.get(`/api/photos/${photoId}`)
                    .then(response => {
                        const photo = response.data;

                        // 填充详情视图
                        const detailPhotoImg = document.getElementById('detail-photo-img');
                        const detailPhotoTitle = document.getElementById('detail-photo-title');
                        const detailPhotoDescription = document.getElementById('detail-photo-description');
                        const detailPhotoUploader = document.getElementById('detail-photo-uploader');
                        const detailPhotoDate = document.getElementById('detail-photo-date');
                        const detailPhotoCategory = document.getElementById('detail-photo-category');
                        const detailPhotoAlbum = document.getElementById('detail-photo-album');
                        const detailPhotoIsShared = document.getElementById('detail-photo-is-shared');

                        // 填充编辑表单
                        const editPhotoId = document.getElementById('edit-photo-id');
                        const editPhotoTitle = document.getElementById('edit-photo-title');
                        const editPhotoDescription = document.getElementById('edit-photo-description');
                        const editPhotoCategory = document.getElementById('edit-photo-category');
                        const editPhotoDate = document.getElementById('edit-photo-date');
                        const editPhotoIsShared = document.getElementById('edit-photo-is-shared');

                        if (elementExists(detailPhotoImg)) detailPhotoImg.src = photo.image_url;
                        if (elementExists(detailPhotoTitle)) detailPhotoTitle.textContent = photo.title;
                        if (elementExists(detailPhotoDescription)) detailPhotoDescription.textContent = photo.description || '无描述';
                        if (elementExists(detailPhotoUploader)) detailPhotoUploader.textContent = `上传者: ${photo.uploaded_by?.nickname || '未知'}`;
                        if (elementExists(detailPhotoDate)) detailPhotoDate.textContent = photo.date_taken ? `拍摄日期: ${new Date(photo.date_taken).toLocaleDateString()}` : '未设置拍摄日期';
                        if (elementExists(detailPhotoCategory)) detailPhotoCategory.textContent = photo.category ? `分类: ${photo.category}` : '未设置分类';
                        if (elementExists(detailPhotoAlbum)) detailPhotoAlbum.textContent = `相册: ${photo.album?.name || '未知'}`;
                        if (elementExists(detailPhotoIsShared)) detailPhotoIsShared.checked = photo.is_shared;

                        if (elementExists(editPhotoId)) editPhotoId.value = photo.id;
                        if (elementExists(editPhotoTitle)) editPhotoTitle.value = photo.title;
                        if (elementExists(editPhotoDescription)) editPhotoDescription.value = photo.description || '';
                        if (elementExists(editPhotoCategory)) editPhotoCategory.value = photo.category || '';
                        if (elementExists(editPhotoDate)) editPhotoDate.value = photo.date_taken ? new Date(photo.date_taken).toISOString().split('T')[0] : '';
                        if (elementExists(editPhotoIsShared)) editPhotoIsShared.checked = photo.is_shared;

                        // 切换到详情视图
                        const photoDetailView = document.getElementById('photo-detail-view');
                        const photoEditView = document.getElementById('photo-edit-view');
                        if (elementExists(photoDetailView)) photoDetailView.classList.remove('hidden');
                        if (elementExists(photoEditView)) photoEditView.classList.add('hidden');

                        elements.photoDetailModal.classList.remove('hidden');
                    })
                    .catch(error => {
                        console.error('获取照片详情失败:', error);
                        showToast('获取照片详情失败，请重试', 'error');
                    });
            }

            // 保存照片编辑
            function savePhotoChanges() {
                const photoId = document.getElementById('edit-photo-id')?.value;
                if (!photoId) {
                    console.error('照片ID不存在');
                    return;
                }

                const updatedData = {
                    title: document.getElementById('edit-photo-title')?.value.trim() || '',
                    description: document.getElementById('edit-photo-description')?.value.trim() || '',
                    category: document.getElementById('edit-photo-category')?.value || '',
                    date_taken: document.getElementById('edit-photo-date')?.value || '',
                    is_shared: document.getElementById('edit-photo-is-shared')?.checked || false
                };

                axios.put(`/api/photos/${photoId}`, updatedData)
                    .then(response => {
                        showToast('照片更新成功');
                        // 切换回详情视图并刷新数据
                        showPhotoDetail(photoId);
                        // 同步更新所有相关视图
                        syncAllViews();
                    })
                    .catch(error => {
                        console.error('更新照片失败:', error);
                        showToast('更新照片失败，请重试', 'error');
                    });
            }

            // 更新照片共享状态
            function updatePhotoSharedStatus(photoId, isShared) {
                axios.put(`/api/photos/${photoId}`, {
                    is_shared: isShared
                })
                .then(response => {
                    showToast('共享状态已更新');
                    syncAllViews();
                })
                .catch(error => {
                    console.error('更新照片共享状态失败:', error);
                    showToast('更新共享状态失败，请重试', 'error');
                    // 恢复原来的状态
                    const detailPhotoIsShared = document.getElementById('detail-photo-is-shared');
                    if (elementExists(detailPhotoIsShared)) {
                        detailPhotoIsShared.checked = !isShared;
                    }
                });
            }

            // 显示删除照片确认
            window.showDeletePhotoConfirm = function(photoId) {
                const deleteModalTitle = document.getElementById('delete-modal-title');
                const deleteModalMessage = document.getElementById('delete-modal-message');
                const deleteItemId = document.getElementById('delete-item-id');
                const deleteItemType = document.getElementById('delete-item-type');

                if (elementExists(deleteModalTitle) && elementExists(deleteModalMessage) &&
                    elementExists(deleteItemId) && elementExists(deleteItemType) && elementExists(elements.deleteConfirmModal)) {

                    deleteModalTitle.textContent = '确认删除照片';
                    deleteModalMessage.textContent = '您确定要删除这张照片吗？此操作无法撤销。';
                    deleteItemId.value = photoId;
                    deleteItemType.value = 'photo';
                    elements.deleteConfirmModal.classList.remove('hidden');
                }
            }

            // 显示删除相册确认
            window.showDeleteAlbumConfirm = function(albumId, albumName) {
                const deleteModalTitle = document.getElementById('delete-modal-title');
                const deleteModalMessage = document.getElementById('delete-modal-message');
                const deleteItemId = document.getElementById('delete-item-id');
                const deleteItemType = document.getElementById('delete-item-type');

                if (elementExists(deleteModalTitle) && elementExists(deleteModalMessage) &&
                    elementExists(deleteItemId) && elementExists(deleteItemType) && elementExists(elements.deleteConfirmModal)) {

                    deleteModalTitle.textContent = '确认删除相册';
                    deleteModalMessage.textContent = `您确定要删除相册"${albumName}"吗？相册中的所有照片也将被删除，此操作无法撤销。`;
                    deleteItemId.value = albumId;
                    deleteItemType.value = 'album';
                    elements.deleteConfirmModal.classList.remove('hidden');
                }
            }

            // 删除照片
            function deletePhoto(photoId) {
                if (!elementExists(elements.deleteConfirmModal)) return;

                axios.delete(`/api/photos/${photoId}`)
                    .then(response => {
                        showToast('照片删除成功');
                        elements.deleteConfirmModal.classList.add('hidden');
                        // 同步更新所有相关视图
                        syncAllViews();
                    })
                    .catch(error => {
                        console.error('删除照片失败:', error);
                        showToast('删除照片失败，请重试', 'error');
                    });
            }

            // 删除相册
            function deleteAlbum(albumId) {
                if (!elementExists(elements.deleteConfirmModal)) return;

                axios.delete(`/api/albums/${albumId}`)
                    .then(response => {
                        showToast('相册删除成功');
                        elements.deleteConfirmModal.classList.add('hidden');
                        // 同步更新所有相关视图
                        syncAllViews();
                    })
                    .catch(error => {
                        console.error('删除相册失败:', error);
                        showToast('删除相册失败，请重试', 'error');
                    });
            }

            // 查看相册照片
            window.viewAlbumPhotos = function(albumId) {
                if (!elementExists(elements.albumsView) || !elementExists(elements.photosView) ||
                    !elementExists(elements.allPhotosBtn) || !elementExists(elements.albumsBtn) || !elementExists(elements.albumFilter)) {
                    return;
                }

                // 切换到照片视图
                elements.albumsView.classList.add('hidden');
                elements.photosView.classList.remove('hidden');
                elements.allPhotosBtn.classList.add('bg-primary', 'text-white');
                elements.allPhotosBtn.classList.remove('border', 'border-gray-300', 'hover:bg-gray-100');
                elements.albumsBtn.classList.remove('bg-primary', 'text-white');
                elements.albumsBtn.classList.add('border', 'border-gray-300', 'hover:bg-gray-100');

                // 设置筛选器
                elements.albumFilter.value = albumId;

                // 加载指定相册的照片
                loadPhotosWithFilters();
            }

            // 打开设置封面模态框
            window.openSetCoverModal = function(albumId, albumName) {
                if (!elementExists(elements.setCoverModal) || !elementExists(elements.setCoverAlbumId) ||
                    !elementExists(elements.setCoverAlbumName) || !elementExists(elements.coverPhotosContainer) ||
                    !elementExists(elements.coverLoading) || !elementExists(elements.noCoverPhotos)) {
                    return;
                }

                // 设置相册ID和名称
                elements.setCoverAlbumId.value = albumId;
                elements.setCoverAlbumName.textContent = `设置"${albumName}"的封面`;

                // 重置状态
                elements.coverPhotosContainer.innerHTML = '';
                elements.coverLoading.classList.remove('hidden');
                elements.noCoverPhotos.classList.add('hidden');
                elements.confirmSetCover.disabled = true;

                // 加载该相册的所有照片
                axios.get(`/api/albums/${albumId}/photos`)
                    .then(response => {
                        elements.coverLoading.classList.add('hidden');
                        const photos = response.data;

                        if (!photos || photos.length === 0) {
                            elements.noCoverPhotos.classList.remove('hidden');
                            return;
                        }

                        // 获取当前封面照片ID
                        let currentCoverId = null;
                        axios.get(`/api/albums/${albumId}`)
                            .then(albumResponse => {
                                currentCoverId = albumResponse.data.cover_photo_id;

                                // 渲染照片选择器
                                photos.forEach(photo => {
                                    const photoDiv = document.createElement('div');
                                    photoDiv.className = `photo-card cursor-pointer relative ${currentCoverId == photo.id ? 'cover-selected' : 'cover-selector'}`;
                                    photoDiv.setAttribute('data-photo-id', photo.id);

                                    photoDiv.innerHTML = `
                                        <div class="aspect-square bg-gray-100 overflow-hidden">
                                            <img src="${photo.image_url}" alt="${photo.title}"
                                                 class="w-full h-full object-cover">
                                            <div class="cover-select-overlay">
                                                <i class="fa fa-check-circle text-2xl text-white"></i>
                                            </div>
                                            ${currentCoverId == photo.id ? `
                                                <div class="absolute top-2 right-2 bg-primary text-white text-xs px-2 py-0.5 rounded">
                                                    当前封面
                                                </div>
                                            ` : ''}
                                        </div>
                                        <div class="p-2">
                                            <h3 class="font-medium text-gray-800 truncate text-sm">${photo.title}</h3>
                                        </div>
                                    `;

                                    elements.coverPhotosContainer.appendChild(photoDiv);

                                    // 点击选择照片作为封面
                                    photoDiv.addEventListener('click', function() {
										event.stopPropagation();
                                        // 移除其他照片的选中状态
                                        document.querySelectorAll('.cover-selected').forEach(el => {
                                            el.classList.remove('cover-selected');
                                            el.classList.add('cover-selector');
                                        });

                                        // 设置当前照片为选中状态
                                        this.classList.remove('cover-selector');
                                        this.classList.add('cover-selected');

                                        // 启用确认按钮
                                        elements.confirmSetCover.disabled = false;
                                    });
                                });
                            })
                            .catch(error => {
                                console.error('获取相册信息失败:', error);
                                // 即使获取当前封面失败，也继续渲染照片
                                renderCoverPhotos(photos, null);
                            });
                    })
                    .catch(error => {
                        console.error('加载相册照片失败:', error);
                        elements.coverLoading.classList.add('hidden');
                        elements.coverPhotosContainer.innerHTML = '<p class="text-red-500">加载照片失败，请重试</p>';
                    });

                // 显示模态框
                elements.setCoverModal.classList.remove('hidden');
            }

            // 渲染封面选择照片
            function renderCoverPhotos(photos, currentCoverId) {
                photos.forEach(photo => {
                    const photoDiv = document.createElement('div');
                    photoDiv.className = `photo-card cursor-pointer relative ${currentCoverId == photo.id ? 'cover-selected' : 'cover-selector'}`;
                    photoDiv.setAttribute('data-photo-id', photo.id);

                    photoDiv.innerHTML = `
                        <div class="aspect-square bg-gray-100 overflow-hidden">
                            <img src="${photo.image_url}" alt="${photo.title}"
                                 class="w-full h-full object-cover">
                            <div class="cover-select-overlay">
                                <i class="fa fa-check-circle text-2xl text-white"></i>
                            </div>
                            ${currentCoverId == photo.id ? `
                                <div class="absolute top-2 right-2 bg-primary text-white text-xs px-2 py-0.5 rounded">
                                    当前封面
                                </div>
                            ` : ''}
                        </div>
                        <div class="p-2">
                            <h3 class="font-medium text-gray-800 truncate text-sm">${photo.title}</h3>
                        </div>
                    `;

                    elements.coverPhotosContainer.appendChild(photoDiv);

                    // 点击选择照片作为封面
                    photoDiv.addEventListener('click', function() {
                        // 移除其他照片的选中状态
                        document.querySelectorAll('.cover-selected').forEach(el => {
                            el.classList.remove('cover-selected');
                            el.classList.add('cover-selector');
                        });

                        // 设置当前照片为选中状态
                        this.classList.remove('cover-selector');
                        this.classList.add('cover-selected');

                        // 启用确认按钮
                        elements.confirmSetCover.disabled = false;
                    });
                });
            }

            // 设置相册封面
			function setAlbumCover(albumId, photoId) {
				if (!albumId || !photoId) return;

				axios.put(`/api/albums/${albumId}/cover`, {
					cover_photo_id: photoId
				})
				.then(response => {
					showToast('相册封面设置成功');
					if (elementExists(elements.setCoverModal)) {
						resetCoverModalState(); // 使用重置函数
						elements.setCoverModal.classList.add('hidden');
					}
					// 重新加载相册列表以显示新封面
					loadAlbums();
				})
				.catch(error => {
					console.error('设置相册封面失败:', error);
					showToast('设置相册封面失败，请重试', 'error');
				});
			}
             

            // 同步更新所有视图
            function syncAllViews() {
                // 重新加载相册列表
                loadAlbums();
                // 重新加载相册下拉框
                loadAlbumsForSelect();
                // 重新加载相册筛选器
                loadAlbumsForFilter();
                // 如果当前在照片视图，重新加载照片
                if (elementExists(elements.photosView) && !elements.photosView.classList.contains('hidden')) {
                    loadPhotosWithFilters();
                }
            }

            // 显示提示消息
            function showToast(message, type = 'success') {
                // 创建 Toast 元素
                const toast = document.createElement('div');
                toast.className = `toast ${type === 'success' ? 'toast-success' : 'toast-error'}`;
                toast.textContent = message;

                // 添加到页面
                document.body.appendChild(toast);

                // 3秒后移除
                setTimeout(() => {
                    toast.classList.add('opacity-0');
                    setTimeout(() => toast.remove(), 300);
                }, 3000);
            }

            // 格式化日期
            function formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
            }

            // HTML转义，防止XSS
            function escapeHtml(unsafe) {
                if (!unsafe) return '';
                return unsafe
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            }

            // 修复showPhotoDetail未定义的问题，绑定到window对象
            window.showPhotoDetail = showPhotoDetail;
        });
    </script>
</body>
</html>
